<%@ page pageEncoding="UTF-8"%>
<%@ include file="/common/token.jsp"%>
<%@ include file="/common/user.jsp"%>
<%@ include file="/common/visit.jsp"%>
<%@ include file="/common/operatehistory.jsp"%>
<%
	// 填写随访量表
	Integer uid = token.getUid();
	Integer visitId =  input.getInt("point_id");
	Integer surveyId =  input.getInt("survey_id");
	List<SurveyAnswer> anwserList = QBuilder.db("basedb").select().from("SurveyAnswer").where(new Where("hospital=", hospital).and("uid=", uid).and("surveyId=", surveyId).and("visitId=", visitId)).query().getResultObj();
	if (!isEmpty(anwserList)) {
		SurveyAnswer surveyAnswer = anwserList.get(0);
		String date = DateUtil.formatDateByFormat(new Date(surveyAnswer.getcTime()), DateUtil.DATETIME_FORMAT);
		Tools.encryptPrint(out, new Message(30031, String.format("您于%s已经提交过该量表，不能重复提交", new Object[]{date})));
		return;
	}
	String json = Tools.decryptStr(input.getDesc("quests"));
	List<Map> quests = JSONUtil.fromJson(json, new TypeReference<List<Map>>(){});
	long time = System.currentTimeMillis();
	List<SurveyAnswer> surveyAnswers = new ArrayList<SurveyAnswer>();
	int sumScore = 0;
	for (int t = 0; quests != null && t < quests.size(); t++) {
		Map quest = (Map)quests.get(t);
		int questId = Tools.getInt((quest.get("quest_id") + "").replace(".0", ""), 0);
		int type = Tools.getInt((quest.get("type") + "").replace(".0", ""), 0);
		List options = (List)quest.get("options");
		for (int j = 0; options != null && j < options.size(); j++) {
			quest = (Map)options.get(j);
			SurveyAnswer surveyAnswer = new SurveyAnswer();
			surveyAnswer.setSurveyId(surveyId);
			surveyAnswer.setQuestId(questId);
			surveyAnswer.setContent(Tools.getDesc(quest.get("content") + "", ""));
			if (type == SURVEY_QUESTION_TYPE_SINGLE_V2 || type == SURVEY_QUESTION_TYPE_MULTI_V2 ||type == SURVEY_QUESTION_TYPE_SINGLE_NOMUST_V2 ||type == SURVEY_QUESTION_TYPE_GRADE_V2 )
				surveyAnswer.setContent(Tools.getDesc(quest.get("option_id") + "", "").replace(".0", ""));
			surveyAnswer.setHospital(hospital);
			surveyAnswer.setcTime(time);
			surveyAnswer.setUid(uid);
			surveyAnswer.setScore(Tools.getInt(Tools.getDesc(quest.get("score")).replace(".0", "") + "", 0));
			sumScore += surveyAnswer.getScore();
			surveyAnswer.setVisitId(visitId);
			surveyAnswer.setType(type);
			surveyAnswers.add(surveyAnswer);
		}
	}
	List<Visit> visits = QBuilder.db("basedb").queryHql("from Visit where id = " + visitId);
	if (visits.size() > 0) {
		Visit v = visits.get(0);
		v.setScore(sumScore);
		v.setIsconfirmed(CONFIRMED);
		v.setReconfirmedTime(DateUtil.formatDateByFormat(new Date(), DateUtil.DATETIME_FORMAT));
		DBTools.db("basedb").modItem(v, v.getId());
	}
	DBTools.db("basedb").addItem(surveyAnswers);
	Tools.encryptPrint(out, msg);
%>